//
//  FSHomeViewController+BluetoothData.m
//  FSiOSClient
//
//  Created by purlible on 2024/8/23.
//

#import "FSHomeViewController+BluetoothData.h"
#import "FSHomeViewController+BluetoothList.h"
#import "FSPeripheralInfo.h"

@implementation FSHomeViewController (BluetoothData)

#pragma mark --  初始化蓝牙库
- (void)initBabyBluetooth
{
    self.services = [[NSMutableArray alloc]init];
    //初始化BabyBluetooth 蓝牙库
    self.baby = [BabyBluetooth shareBabyBluetooth];
    //设置蓝牙委托
    [self babyDelegate];
}

#pragma mark -- 开始扫描外设
- (void)beginScanForPeripherals
{
    //蓝牙关闭
    if (self.bluetoothState == 0) 
    {
        [self showTextInWindow:NSLocalizedString(@"please_open_bluetooth", nil)];
        return;
    }
    else
    {
        [self showTextInWindow:NSLocalizedString(@"bluetooth_search_underway", nil)];
        self.baby.scanForPeripherals().begin();
    }
}
#pragma mark -- 停止扫描外设
- (void)endScanForPeripherls
{
    [self.baby cancelScan];
}

#pragma mark -- 设置蓝牙委托
-(void)babyDelegate
{
    FSWeakSelf;
    BabyRhythm *rhythm = [[BabyRhythm alloc]init];
    
    //1.蓝牙状态更新监控
    [self.baby setBlockOnCentralManagerDidUpdateState:^(CBCentralManager *central) {
        weakSelf.bluetoothState = central.state;
        if (central.state == CBManagerStatePoweredOn) {
            weakSelf.bluetoothState = 1;
            DDLogDebug(@"蓝牙设备打开");
            [weakSelf beginScanForPeripherals];
        }
        if (central.state == CBManagerStatePoweredOff) {
            weakSelf.bluetoothState = 0;
            weakSelf.bluetoothConnectState = 0;
            [weakSelf disConnectUpdateStatus];
            DDLogDebug(@"蓝牙设备关闭");
        }
    }];
    //2.设置查找外设过滤器
    [self.baby setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
        return YES;
    }];
    //3.扫描到设备
    [self.baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        if (peripheral.name) {
            DDLogDebug(@"搜索到了设备:%@",peripheral.name);
            [weakSelf insertTableView:peripheral advertisementData:advertisementData RSSI:RSSI];
        }
    }];
    //4.设置蓝牙连接过滤
//    [baby setFilterOnConnectToPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
//        return YES;
//    }];
    //5.设备连接成功
    [self.baby setBlockOnConnected:^(CBCentralManager *central, CBPeripheral *peripheral) {
        DDLogDebug(@"设备：%@--连接成功",peripheral.name);
        weakSelf.bluetoothConnectState = 1;
        [weakSelf showTextInWindow:NSLocalizedString(@"bluetooth_connect_success", nil)];
        [weakSelf connectSuccessUpdateStatus];
    }];
    //6.设备连接失败
    [self.baby setBlockOnFailToConnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        weakSelf.bluetoothConnectState = 0;
        DDLogDebug(@"设备：%@--连接失败",peripheral.name);
        [weakSelf showTextInWindow:NSLocalizedString(@"bluetooth_connect_fail", nil)];
    }];
    //7.设备断开连接
    [self.baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        DDLogDebug(@"设备：%@--断开连接",peripheral.name);
        weakSelf.bluetoothConnectState = 0;
        [weakSelf showTextInWindow:NSLocalizedString(@"bluetooth_disconnect", nil)];
        //改变显示状态
        [weakSelf disConnectBluetooth];
        [weakSelf beginScanForPeripherals];
    }];
    //8.发现服务
    [self.baby setBlockOnDiscoverServices:^(CBPeripheral *peripheral, NSError *error) {
        for (CBService * service in peripheral.services) {
            DDLogDebug(@"发现服务:%@",service.UUID);
        }
        [rhythm beats];
    }];
    //9.设置服务特征
    [self.baby setBlockOnDiscoverCharacteristics:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
        for (CBCharacteristic *c in service.characteristics) {
            DDLogDebug( @"服务特征 :%@",c.UUID);
            NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
            int sect = -1;
            for (int i=0;i<self.services.count;i++) {
                FSPeripheralInfo *info = [weakSelf.services objectAtIndex:i];
                if (info.serviceUUID == service.UUID) {
                    sect = i;
                }
            }
            if (sect != -1) {
                FSPeripheralInfo *info =[weakSelf.services objectAtIndex:sect];
                for (int row=0;row<service.characteristics.count;row++) {
                    CBCharacteristic *c = service.characteristics[row];
                    [info.characteristics addObject:c];
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:sect];
                    [indexPaths addObject:indexPath];
                }
            }
        }
    }];
    //10.读取特征值
    [self.baby setBlockOnReadValueForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        DDLogDebug(@"特征名称:%@ === 特征值:%@",characteristics.UUID,characteristics.value);
    }];
    //11.发现特征值描述
    [self.baby setBlockOnDiscoverDescriptorsForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristic, NSError *error) {
        DDLogDebug(@"发现特征名称:%@ === 特征值:%@",characteristic.UUID,characteristic.value);
        if ([characteristic.UUID.UUIDString isEqualToString:kCharacteristicOldUUID] || 
            [characteristic.UUID.UUIDString isEqualToString:kCharacteristicNewUUID]) 
        {
            weakSelf.characteristicNotify = characteristic;
        }
    }];
    //12.设置读取特征值描述值
    [self.baby setBlockOnReadValueForDescriptors:^(CBPeripheral *peripheral, CBDescriptor *descriptor, NSError *error) {
        
        if ([descriptor.characteristic.UUID.UUIDString isEqualToString:kCharacteristicOldUUID])
        {
            NSString *flag = @"false";
            NSString *receiveJS = [NSString stringWithFormat:@"window.useNewProtocol('%@')",flag];
            [weakSelf.webView evaluateJavaScript:receiveJS completionHandler:nil];
            
            weakSelf.characteristic = descriptor.characteristic;
            //停止扫描
            [weakSelf endScanForPeripherls];
        }
        else if ( [descriptor.characteristic.UUID.UUIDString isEqualToString:kCharacteristicNewUUID])
        {
            NSString *flag = @"true";
            NSString *receiveJS = [NSString stringWithFormat:@"window.useNewProtocol('%@')",flag];
            [weakSelf.webView evaluateJavaScript:receiveJS completionHandler:nil];
            
            weakSelf.characteristic = descriptor.characteristic;
            //停止扫描
            [weakSelf endScanForPeripherls];
        }
    }];
}

#pragma mark -- 连接成功 刷新列表
- (void)connectSuccessUpdateStatus
{
    for (NSMutableDictionary *item in self.peripheralDataArray) {
        NSString * code = [item objectForKey:@"code"];
        if ([self.peripheralCode isEqualToString:code]) {
            //更新蓝牙列表
            [item setValue:@"1" forKey:@"status"];
        }else{
            [item setValue:@"0" forKey:@"status"];
        }
    }
    [self updateH5BluetoothList];
}
#pragma mark -- 断开连接 刷新列表
- (void)disConnectUpdateStatus
{
    for (NSMutableDictionary *item in self.peripheralDataArray) {
        [item setValue:@"0" forKey:@"status"];
    }
    [self updateH5BluetoothList];
}

#pragma mark -- 连接蓝牙
-(void)connectBluetooth
{
    [self.baby cancelAllPeripheralsConnection];
    DDLogDebug(@"开始连接设备");
    FSWeakSelf
    self.baby.having(weakSelf.currPeripheral).
    then.connectToPeripherals().discoverServices().discoverCharacteristics().
    readValueForCharacteristic().discoverDescriptorsForCharacteristic().
    readValueForDescriptors().begin();
}

#pragma mark -- 断开蓝牙连接
-(void)disConnectBluetooth
{
    //清除上一次扫描数据
    if (self.peripheralDataArray) {
        [self.peripheralDataArray removeAllObjects];
    }
    if (self.table) {
        [self.table reloadData];
    }
}


#pragma mark -- 下发蓝牙指令
/**
 下发蓝牙指令
 @param command 蓝牙指令 中文
 @param response 设备返回数据
 */
- (void)downBluetoothCommandString:(NSString *)command response:(DownloadCommandResponse)response;
{
    NSData *data = [FSTools convertHexStrToData:command];
    DDLogDebug(@"下发指令%@ \n下发设备数据: %@",command, data);
    
    if (!self.characteristic) return;
    
    CBCharacteristicWriteType writeType = CBCharacteristicWriteWithoutResponse;
    if ([self.characteristic.UUID.UUIDString isEqualToString:kCharacteristicNewUUID]) writeType = CBCharacteristicWriteWithResponse;
    
    [self.currPeripheral writeValue:data forCharacteristic:self.characteristic type:writeType];
    
    //监听通知
    [self.currPeripheral setNotifyValue:YES forCharacteristic:self.characteristic];
    [self.baby notify:self.currPeripheral characteristic:self.characteristic block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        DDLogDebug(@"resume notify block");
    }];
    //notify
    if(self.currPeripheral.state != CBPeripheralStateConnected) {
        return;
    }
    
    [self.baby notify:self.currPeripheral characteristic:self.characteristic block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        NSData * responData = characteristics.value;
        NSString * hexString = [FSTools convertDataToHexStr:responData];
        if (response) {
            DDLogDebug(@"下发指令%@ \n下发设备数据: %@ \n 回写数据 %@",command, data,hexString);
            response(hexString);
        }
    }];
}



@end
